package com.example.springboot.service.admin.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.mapper.WebsiteResourceMapper;
import com.example.springboot.mapper.WebsiteTitleMapper;
import com.example.springboot.model.entity.WebsiteResource;
import com.example.springboot.model.entity.WebsiteTitle;
import com.example.springboot.model.form.Result;
import com.example.springboot.model.req.admin.WebsiteResourceReq;
import com.example.springboot.model.vo.WebsiteResourceVO;
import com.example.springboot.model.vo.WebsiteTitleVO;
import com.example.springboot.service.admin.WebsiteResourceService;
import com.example.springboot.utils.CopyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Stream;

/**
 * @
 *
 * @author zf
 * @since 2021-05-17
 */
@Service
public class WebsiteResourceServiceImpl extends ServiceImpl<WebsiteResourceMapper, WebsiteResource> implements WebsiteResourceService {

    @Resource
    WebsiteTitleMapper websiteTitleMapper;
    @Override
    public Result getPage(WebsiteResourceReq req) {
        List<WebsiteTitle> websiteTitles = websiteTitleMapper.selectList(new LambdaQueryWrapper<WebsiteTitle>()
                .eq(WebsiteTitle::getInvalid, 0)
                .orderByDesc(WebsiteTitle::getSort)
                .orderByDesc(WebsiteTitle::getCreateTime));
        return Result.buildSuccess(websiteTitles.stream().map(e -> {
            WebsiteTitleVO vo = CopyUtil.copyObject(e, WebsiteTitleVO.class);
            List<WebsiteResource> list = list(new LambdaQueryWrapper<WebsiteResource>()
                    .eq(WebsiteResource::getWebsiteTitleId, e.getId())
                    .eq(WebsiteResource::getInvalid, 0)
                    .orderByDesc(WebsiteResource::getSort)
                    .orderByDesc(WebsiteResource::getCreateTime));
            vo.setWebsiteResourceVO(CopyUtil.copyList(list, WebsiteResourceVO.class));
            return vo;
        }));
    }

    @Override
    public Result addInfo(WebsiteResourceReq req) {
        //主表复制元素
        WebsiteResource websiteResource = CopyUtil.copyObject(req, WebsiteResource.class);
        boolean flag;
        if (req.getId() != null) {
            flag = updateById(websiteResource);
        } else {
            flag = save(websiteResource);
        }
        if (flag) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

    @Override
    public Result deleteInfos(String ids) {
        if (update(new UpdateWrapper<WebsiteResource>().lambda()
                .set(WebsiteResource::getInvalid, 1)
                .inSql(WebsiteResource::getId, ids)
        )) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

}
